package dfsketches.gr3d;

import dfsketches.visualizer_2d.ColorSolver;

public class TerrainConstructor {
	
	private int[][] map;
	private float w;
	private float h;
	private float d;
	ColorSolver cols;
	
	public TerrainConstructor(int[][] map, float sx, float sy, float sz, ColorSolver cols) {
		this.map = map;
		w = sx;
		d = sy;
		h = sz;
		this.cols = cols;
	}
	
	public Model construct() {
		BoneConstructor bctr = new BoneConstructor();
		
		int size = map.length;
		float x = 0;
		float z = 0;
		float dx = 1f / size;
		float dz = 1f / size;
		Vertex[][] vs = new Vertex[size][size];
		for (int ix = 0; ix < size; ix++) {
			for (int iz = 0; iz < size; iz++) {
				bctr.addVertex(vs[ix][iz] = new Vertex(x, map[ix][iz], z));
				z += dz;
			}
			z = 0f;
			x += dx;
		}
		
		ModelConstructor cnstr = new ModelConstructor();
		cnstr.setMainBone(bctr.construct());
		for (int ix = 0; ix < size-1; ix++) {
			for (int iz = 0; iz < size-1; iz++) {
				Vertex v00 = vs[ix][iz];
				Vertex v01 = vs[ix][iz+1];
				Vertex v10 = vs[ix+1][iz];
				Vertex v11 = vs[ix+1][iz+1];
				
				int h00 = map[ix][iz];
				int h01 = map[ix][iz+1];
				int h10 = map[ix+1][iz];
				int h11 = map[ix+1][iz+1];
				
				int color = cols.getColor((h00 + h01 + h10 + h11) / 4);
				
				if (h00 + h11 <= h01 + h10) {
					cnstr.addRectangle(color, v10, v11, v00, v01);
				} else {
					cnstr.addRectangle(color, v00, v01, v10, v11);
				}
			}
		}
		
		cnstr.apply(Matrix3D.getScaleMatrix(w, d, h));
		return cnstr.construct();
	}
	
}
